<template>
  <a-drawer :open="visible" title="入库详情" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-card size="small" title="基本信息">
      <a-descriptions size="small" :column="3">
        <!-- <a-descriptions-item label="单据编号">{{ options.no }}</a-descriptions-item> -->
        <a-descriptions-item label="源订单号">{{ options.related?.no ?? options.related?.order_no }}</a-descriptions-item>
        <template v-if="[INTO_STATUS_ENUM.PurchaseOrder.value, INTO_STATUS_ENUM.CompanyTransferOrder.value].includes(options.related_type)">
          <a-descriptions-item label="经销商">{{ options.dealer?.name }}</a-descriptions-item>
          <a-descriptions-item label="供应商" v-if="options.related_type === INTO_STATUS_ENUM.PurchaseOrder.value">
            {{ options.related?.supplier?.name ?? '-' }}
          </a-descriptions-item>
        </template>
        <template v-if="[INTO_STATUS_ENUM.AbnormalOrder.value, INTO_STATUS_ENUM.ReturnOrder.value].includes(options.related_type)">
          <a-descriptions-item label="司机">{{ options.related?.customer?.name }}</a-descriptions-item>
        </template>
        <a-descriptions-item label="入货仓库"> {{ options.related?.warehouse?.name }}({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', options.related?.warehouse?.attribute_type) }} )</a-descriptions-item>
        <a-descriptions-item label="入库类型">
          <span>{{ getDescByValue('INTO_STATUS_ENUM', options.related_type) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="入库状态">
          <span>{{ getDescByValue('STORE_STATUS_ENUM', options.into_status) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="签收数量">{{ options.sign_num }}</a-descriptions-item>
        <a-descriptions-item label="签收金额">{{ Number(options.sign_amount).toFixed(2) }}</a-descriptions-item>
        <a-descriptions-item label="订单金额">{{ Number(options.order_amount).toFixed(2) }}</a-descriptions-item>
        <a-descriptions-item label="源单备注">{{ options.related?.remark }}</a-descriptions-item>
        <a-descriptions-item label="签收备注">{{ options.sign_remark }}</a-descriptions-item>
        <a-descriptions-item label="单据日期">{{ options.create_time }}</a-descriptions-item>
        <a-descriptions-item label="打印次数">{{ printLog?.print_count }}</a-descriptions-item>
        <a-descriptions-item label="最近打印时间">{{ printLog?.update_time }}</a-descriptions-item>
        <a-descriptions-item label="最近打印人">{{ printLog?.printerName }}</a-descriptions-item>
      </a-descriptions>
    </a-card>
    <a-card class="smart-margin-top10" size="small" :tab-list="tabList" :active-tab-key="activeKey" @tabChange="(key) => (activeKey = key)">
      <template #customTab="{ tab }">
        <span class="ant-card-head-title" :style="compactModeClass">
          {{ tab }}
        </span>
      </template>
      <template v-if="activeKey === 'inventory'">
        <a-table :dataSource="dataList" :columns="columns" :pagination="false" :scroll="{ x: 'max-content' }" rowKey="id" size="small" bordered :showExpandColumn="false" expandRowByClick>
          <template #expandedRowRender="{ record }">
            <div class="content">
              <!-- 展示 detail 数据 -->
              <div v-for="(item, index) in record.batch" :key="index" class="parent">
                <div class="div1">批次：{{ item.batch_time }}</div>
                <div class="div2">数量：{{ item.initial_quantity }}</div>
                <div class="div3">仓库：{{ item.warehouse_name }}</div>
                <div class="div3">库位：{{ item.location_code }}</div>
              </div>
            </div>
          </template>
        </a-table>
      </template>
      <template v-if="activeKey === 'log'">
        <PurchaseTracerTimeline :tableData="orderLog" />
      </template>
    </a-card>
    <template #footer>
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import _ from 'lodash'
import { message } from 'ant-design-vue'
import PurchaseTracerTimeline from './purchase-tracer-timeline.vue'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
import { returnOrderApi } from '@/api/business/storage/store-api'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import { INTO_STATUS_ENUM } from '@/constants/business/storage/inwarehouse/in-warehouse-const'
const compactModeClass = inject('compactModeClass')
const loadingStore = useLoadingStore()
const { getDescByValue } = useEnums()
const { transformSpec } = useTransformSpec()
defineExpose({
  showDrawer
})
const emit = defineEmits(['reload-list'])

// ------- -------------- Drawer 显示与隐藏 ---------------------
// 是否展示
const visible = ref(false)
// 详情
const options = ref({})
// 详情tab
const activeKey = ref('inventory')
const tabList = [
  {
    key: 'inventory',
    tab: '商品明细'
  },
  {
    key: 'log',
    tab: '日志记录'
  }
]

function showDrawer(item) {
  options.value = item
  singleDetail(item)
  visible.value = true
}

const onClose = () => {
  visible.value = false
}

// --------------------- 入库商品 ---------------------
const dataList = ref<any[]>([])
const orderLog = ref([])
const printLog = ref({})
const columns = reactive([
  {
    title: '商品名称',
    dataIndex: 'goods_name'
  },
  {
    title: '规格',
    dataIndex: 'spec_name'
  },
  {
    title: '单位',
    dataIndex: 'unit_name'
  },
  {
    title: '数量',
    dataIndex: 'num'
  },
  {
    title: '签收数量',
    dataIndex: 'initial_quantity'
  },
  {
    title: '总计',
    dataIndex: 'sign_amount'
  },
  {
    title: '备注',
    dataIndex: 'remark'
  }
])
// 合并签收批次商品数据与入库单商品数据
function mergeGoodsData(detailGoods: any[], batchGoods: any[]): any[] {
  const list = new Map()
  // 构建以入库单商品数据为key的Map
  for (const item of detailGoods) {
    if (list.has(item.goods_id)) continue
    // 过滤条件-当前商品ID
    const filterConditions = { goods_id: item.goods_id }
    // 获取当前商品的所有规格信息-detailGoods[index].goods.spec
    const specs = _(detailGoods).find(filterConditions).goods.spec
    // 获取当前商品ID的所有入库单商品数量-num
    const num: number = _(detailGoods).filter(filterConditions).sumBy('base_num')
    // 获取当前商品ID的所有批次商品数据
    const batch = _(batchGoods).filter(filterConditions).value()
    // 获取当前商品ID的所有批次商品数量-initial_quantity
    const initial_quantity: number = _.sumBy(batch, 'initial_quantity')
    const value = {
      id: item.goods_id,
      goods_name: item.goods.goods_name,
      spec_name: item.spec.spec_name,
      unit_name: item.spec.unit_name,
      num: transformSpec(num, specs),
      initial_quantity: transformSpec(initial_quantity, specs),
      remark: item.remark,
      batch: batch.map((batchRow) => ({
        batch_time: dayjs(batchRow.batch_time).format('YYYY-MM-DD'),
        initial_quantity: transformSpec(batchRow.initial_quantity, specs),
        warehouse_name: `${batchRow.warehouse?.name}(${getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', batchRow.attribute_type)})`,
        location_code: batchRow?.warehouse_location?.code ?? ''
      })),
      sign_amount: _(batch)
        .map(({ sign_amount }) => Number(sign_amount))
        .sumBy()
        .toFixed(2)
    }
    list.set(item.goods_id, value)
  }
  return Array.from(list.values())
}
// 详情
async function singleDetail(rowData) {
  try {
    loadingStore.show()
    const res = await returnOrderApi.detail({ id: rowData.id })
    dataList.value = mergeGoodsData(res.data.detail, res.data.batch)
    orderLog.value = res.data.log
    printLog.value = res.data.printLog
  } catch (e) {
    if (e.msg) {
      message.error(e.msg)
    }
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
</script>
<style lang="less" scoped>
:deep(.ant-table-expanded-row .ant-table-cell) {
  background-color: #e6f4ff;
}
:deep(.ant-table-expanded-row .ant-table-cell:hover) {
  background-color: #e6f4ff;
}
.content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.parent {
  // margin-left: 45%;
  // margin-right: 5%;
  display: grid;
  grid-template-columns: 30% 30% 20% 20%;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.parent:last-of-type {
  border-bottom: none;
}

.div3 {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
  width: 100%; /* 设置一个宽度限制，以便文本超出时能看到效果 */
}
</style>
